'use strict';

const BaseController = require('./BaseController');
class AudioController extends BaseController {
  async index(){
    const { ctx, app } = this;
    const query = ctx.request.query;
    query.model = 'Contact';
    const res = await ctx.service.page.page(query)
    ctx.body = res
  }
  async create(){
    const {ctx,app} = this;
    let params = ctx.request.body;
    params.ip = ctx.request.ip;
    if(params.ip){
      const isExist = await ctx.model.Contact.findOne({where:{ip:params.ip}});
      if(isExist){
        ctx.body = {
          code:0,
          msg:"您已提交过，请勿重新提交。"
        }
        return;
      }
      let locationMsg = {content:""};
      locationMsg = await ctx.curl(`https://api.map.baidu.com/location/ip?ak=l1Lfgzmua3IZbag5Tu5zRdSxHItEzMAy&ip=${params.ip}&coor=bd09ll`).catch(err=>{});
      if(locationMsg.data){
        locationMsg = JSON.parse(locationMsg.data.toString());
        if(locationMsg.content){
          params.address = locationMsg.content.address
        }
      }
    }
    ctx.model.Contact.create(params);
    ctx.body = {
      code:1,
      msg:"创建成功！"
    }
  }
  async destroy(){
    const { ctx, app } = this;
    let id = ctx.params.id;
    if(id){
      await ctx.model.Contact.destroy({where:{id}});
      ctx.body = {code:1,msg:"删除成功"};
    }else{
      ctx.body = {code:0,msg:"删除失败，选择一项删除"};
    }
  }
}

module.exports = AudioController;
